package com.xdf.ecommerce.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义异步任务线程池，异步任务异常捕获处理器
 * @author chanchaw
 * @create 2025-10-28 7:45
 */
@Slf4j
@EnableAsync // 开启 spring 异步任务支持
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(20);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("ecommGoodsServiceAsyncPool-");// 线程池内线程名称的前缀
        executor.setWaitForTasksToCompleteOnShutdown(true);// 等待所有任务结束再关闭线程池
        executor.setAwaitTerminationSeconds(60);// 接受到关闭线程池信号后等待最多60秒后强制关闭线程池
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());// 定义拒绝策略
        executor.initialize();// 初始化线程池
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    /**
     * 异步任务出现异常后使用本类进行捕获处理
     */
    class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
            throwable.printStackTrace();
            log.error("============================================");
            log.error("e-commerce-goods-service异步任务出现异常：[{}], \n出现异常的方法：[{}]\n异常方法参数：[{}]",
                    throwable.getMessage(), method.getName(), JSON.toJSONString(objects));

            // TODO: 可以自定义出现异常后的报警方式，发送邮件、发送微信模板消息等等
        }
    }
}
